package com.shuwen.gcdj.common.exception;

import cn.hutool.log.StaticLog;
import com.shuwen.gcdj.common.api.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.xml.bind.ValidationException;
import java.util.List;

/**
 * @author :杨云山
 * 全局异常处理
 * @date : 2023/3/11 16:25
 */
@ControllerAdvice
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {


    @ExceptionHandler(value = ApiException.class)
    public CommonResult<String> handle(ApiException e) {
        if (e.getErrorCode() != null) {
            return CommonResult.failed(e.getErrorCode());
        }
        return CommonResult.failed(e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST) //设置状态码为 400
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<String> paramExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult exceptions = e.getBindingResult();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                return CommonResult.failed(fieldError.getDefaultMessage());
            }
        }
        return CommonResult.failed("请求参数错误");
    }


    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public CommonResult<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        StaticLog.error(e,"缺少请求参数");
        return CommonResult.failed("缺少请求参数");
    }

//    /**
//     * 400 - Bad Request
//     */
//    @ResponseStatus(HttpStatus.OK)
//    @ExceptionHandler(HttpMessageNotReadableException.class)
//    public CommonResult<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
//        StaticLog.error(e,"参数解析失败");
//        return CommonResult.failed("参数解析失败");
//    }

    /**
     * 400 - Bad Request
     */
//    @ResponseStatus(HttpStatus.OK)
//    @ExceptionHandler(MethodArgumentNotValidException.class)
//    public CommonResult<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
//        StaticLog.error(e,"参数验证失败");
//        BindingResult result = e.getBindingResult();
//        List<FieldError> errors = result.getFieldErrors();
//        return CommonResult.failed(getFieldMessage(errors));
//    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public CommonResult<String> handleBindException(BindException e) {
        StaticLog.error(e,"参数绑定失败");
        BindingResult result = e.getBindingResult();
        List<FieldError> errors = result.getFieldErrors();

        return CommonResult.failed(getFieldMessage(errors));
    }

    /**
     * 获取参数错误信息
     *
     * @param errors
     * @return
     */
    private String getFieldMessage(List<FieldError> errors) {
        StringBuffer sb = new StringBuffer();

        if(errors != null && errors.size() > 0) {
            sb.append(errors.get(0).getDefaultMessage());
        }
        return sb.toString();
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public CommonResult<String> handleValidationException(ValidationException e) {
        StaticLog.error(e,"参数验证失败");
        return CommonResult.failed(e.getMessage());
    }

}
